<template>
  <div>
    <!-- 背景card -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 添加按钮 -->
      <el-button type="primary" size="default" :icon="Plus" @click="addTradeMark">添加</el-button>
      <!-- 表格 -->
      <el-table border style="margin: 10px 0" :data="tmObj.records" v-loading="loading">
        <el-table-column label="序号" type="index" width="90px" align="center">
        </el-table-column>
        <el-table-column label="品牌名称" prop="tmName">
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{row,$index}">
            <a :title="row.tmName">
              <img :src="row.logoUrl" alt="" style="width: 100px; height: 60px; border-radius: 10px">
            </a>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="warning" size="small" :icon="Edit" @click="updateTradeMark(row)"></el-button>
            <!-- 删除按钮 -->
            <el-popconfirm width="250px"  :title="`确定删除${row.tmName}?`" :icon="Delete"  @confirm="handler(row)">
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete"> </el-button>
              </template>
            </el-popconfirm>

                          

           
          </template>

            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <!-- 两个事件
            @size-change="sizeChange"
            @current-change="currentChange" 分页器点击事件
         -->
<el-pagination
        @size-change="sizeChange"
        @current-change="getTradeMarkList"
            v-model:page-size="pageSize"
            v-model:current-page="currentPage"
            :page-sizes="[20, 40, 80, 100]"
            :total="tmObj.total"
            layout=" prev, pager, next, jumper,->,sizes,total"
            background>
            :pager-count="7">
        </el-pagination>
        
      <!-- Dailog对话框 -->
<el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'">
        <el-form  label-width="90px" style="width: 80%" :model="tmParams" :rules="rules" ref="formRef" >
            <!-- 获取品牌名称的地方 -->
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="tmParams.tmName" autocomplete="off" />
          </el-form-item>
          <!-- 获取品牌logo的地方 -->
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <!-- 上传文件 -->
            <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdate"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>

      </el-card>
      
    </div>
</template>

<script setup lang="ts">
import { Delete, Edit, Search, Share, Upload, Plus } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, nextTick } from 'vue'
// 引入提示框组件
import { ElMessage, } from 'element-plus'
// 引入element需要哦的数据类型
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
// 引入数据类型
import type { trademark, trademarkResponseData } from '@/api/product/trademark/model/trademark'
// 引入接口
import { reqTradeMarkList, reqAddUpdateTradeMark,reqDeleteTradeMark } from '@/api/product/trademark/trademark'
// 保存分页器当前页码
let currentPage = ref<number>(1)
// 保存分页器一页几条数据
let pageSize = ref<number>(3)
// 定义控制加载效果的响应式数据
let loading = ref<boolean>(false)
// 定义对话框是否隐藏
let dialogFormVisible = ref<boolean>(false)
// 存储组件实例el-form
let formRef = ref<FormInstance>()
// 定义接收服务器返回的品牌数据
let tmObj = reactive<trademarkResponseData>({
  total: 0,
  records: []
})
// 定义一个品牌对象(新增)
let tmParams = reactive<trademark>({
  tmName: '',
  logoUrl: ''
})


// 挂载完成先获取一次品牌列表数据
onMounted(() => {
  getTradeMarkList()
});

// 获取品牌列表数据    分页器点击,底层传参page
const getTradeMarkList = async (page: number = 1) => {
  // 请求之前加载中
  loading.value = true
  // 整理参数
  currentPage.value = page
  let result = await reqTradeMarkList(currentPage.value, pageSize.value)
  // 保存请求其返回的参数
  tmObj.total = result.total; //品牌总数
  tmObj.records = result.records//一个品牌数据
  // 请求结束,数据已经拿到,不会再加载了
  loading.value = false
}


// 分页器每页几条数据发生变化的回调
const sizeChange = (limit: number) => {
  // 整理数据
  pageSize.value = limit
  // 再次获取列表数据
  getTradeMarkList()

}

// 图片上传成功前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //图片相关的信息
  //外层约束类型
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    //约束大小1024B->1K->1M->1G->1T
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true;
    }
  } else {
    return false;
  }
}

// 图片上传成功后的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //response:上传图片成功服务器返回数据
  //图片学校远程服务器地址
  tmParams.logoUrl = response.data;
}

// 点击确定按钮的回调
const addOrUpdate = async () => {
  formRef.value?.validate(async (success) => {
    // 如果全部字段校验成功
    if (success) {
      // 发请求
      await reqAddUpdateTradeMark(tmParams)
      // 弹框隐藏
      dialogFormVisible.value = false
      //   获取最新的列表数据   有id,修改数据,停留在当前页
      getTradeMarkList(tmParams.id ? currentPage.value : 1)
      // 成功t弹框
      ElMessage({
        message: tmParams.id ? "修改品牌成功" : "添加品牌成功",
        type: "success",
      });
    } else {
      // 失败弹框
      ElMessage({
        message: "添加品牌失败",
        type: "error",
      });
    }
  })
}

// 点击添加按钮的回调
const addTradeMark = () => {
  // 弹窗显示
  dialogFormVisible.value = true
  // 清空上次数据
  tmParams.id = ''
  tmParams.tmName = ''
  tmParams.logoUrl = ''
  //每一次点击添加按钮重置表单验证信息[上一次验证信息清空]
  // formRef.value.resetFields();
  // nextTick当响应式数据发生变化,页面重新渲染的时候,获取最新DOM
  nextTick(() => {
    formRef.value?.resetFields();
  })
}

// 点击修改按钮的回调
const updateTradeMark = (row: trademark) => {
  // 弹窗显示
  dialogFormVisible.value = true

  nextTick(() => {
    formRef.value?.resetFields();
    //  获取当前品牌数据
    tmParams.id = row.id
    tmParams.logoUrl = row.logoUrl
    tmParams.tmName = row.tmName
  })
}

// 自定义表单验证
const validatetmName = (rule: any, value: any, next: any) => {
  if (value.length >= 2 && value.length <10) {
    next()
  } else {
    next(new Error('品牌名称不得小于2大于10'))
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, trigger: 'blur', validator: validatetmName }
  ],
  logoUrl: [{ required: true, message: '请上传LOGO图片' }]
})

// 删除按钮弹框的点击确定事件
const handler =async (row:trademark) =>{
  try {
    // 删除品牌成功
    await reqDeleteTradeMark(row.id)
     //提示信息
     ElMessage({
      type: "success",
      message: `删除${row.tmName}成功`,
    });
    // 再次获取最新列表数据,并停留在当前页
    getTradeMarkList(currentPage.value)
  } catch (error) {
    
  }

}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>